//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer {
    private amount: number = 500;
    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView: LoadingUI;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event: egret.Event) {
        //设置加载进度界面
        //Config to load process interface
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json", "resource/");
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * configuration file loading is completed, start to pre-load the preload resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
        RES.loadGroup("preload");
    }

    /**
     * preload资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent): void {
        if (event.groupName == "preload") {
            this.stage.removeChild(this.loadingView);
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
            RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
            this.createGameScene();
        }
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onItemLoadError(event: RES.ResourceEvent): void {
        console.warn("Url:" + event.resItem.url + " has failed to load");
    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError(event: RES.ResourceEvent): void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete(event);
    }

    /**
     * preload资源组加载进度
     * Loading process of preload resource group
     */
    private onResourceProgress(event: RES.ResourceEvent): void {
        if (event.groupName == "preload") {
            this.loadingView.onProgress(event.itemsLoaded, event.itemsTotal);
        }
    }

    /**
     * 创建游戏场景
     * Create a game scene
     */
    private players: Array<Player> = [];
    private createGameScene(): void {
        this.cacheAsBitmap = false;
        this.stage.dirtyRegionPolicy = egret.DirtyRegionPolicy.OFF;

        //var bg = new egret.Bitmap(RES.getRes("background_jpg"));
        //var tex = RES.getRes("player_json.background");
        var tex = RES.getRes("player_json#background_jpg");
        var bg = new egret.Bitmap(tex);

        this.addChild(bg);

        for (var i = 0; i < this.amount; ++i) {
            //var p = new Player(Math.floor(Math.random() * 4),i.toString(),Math.round(Math.random() * 2 + 3));
            var p = new Player(Math.floor(Math.random() * 4), i.toString(), Math.round(Math.random() * 2 + 3));
            p.x = Math.random() * (this.stage.width + Player.WIDTH * 2);
            p.y = Math.random() * (this.stage.height - Player.HEIGHT);
            this.players.push(p);

            //this.addChild(p)
            /*
            var index = this.$children.length;
            if (child.$parent == this)
                index--;
            return this.$doAddChild(child, index);
             */
            var index = this.$children.length;
            this.$doAddChild(p, index, false);
        }

        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    private onEnterFrame() {
        for (var x in this.players) {
            this.players[x].update();
        }
    }
}

class Player extends egret.Sprite {
    public static WIDTH = 110;
    public static HEIGHT = 110;

    private static RES = [
        [
            "yd-6_01_png",
            "yd-6_02_png",
            "yd-6_03_png",
            "yd-6_04_png",
            "yd-6_05_png",
            "yd-6_06_png",
            "yd-6_07_png",
            "yd-6_08_png",
        ],
        [
            "yd-3_01_png",
            "yd-3_02_png",
            "yd-3_03_png",
            "yd-3_04_png",
            "yd-3_05_png",
            "yd-3_06_png",
            "yd-3_07_png",
            "yd-3_08_png",
        ],
        [
            "yd-2_01_png",
            "yd-2_02_png",
            "yd-2_03_png",
            "yd-2_04_png",
            "yd-2_05_png",
            "yd-2_06_png",
            "yd-2_07_png",
            "yd-2_08_png",
        ],
        [
            "wyd-1_01_png",
            "wyd-1_02_png",
            "wyd-1_03_png",
            "wyd-1_04_png",
            "wyd-1_05_png",
            "wyd-1_06_png",
            "wyd-1_07_png",
            "wyd-1_08_png",
        ]
    ];

    private index: number;
    private anim: number;
    private speed: number;
    private spr: egret.Bitmap;
    private animTime: number;

    public constructor(index: number, name: string, speed: number) {
        super();

        this.cacheAsBitmap = false;
        this.index = index;
        this.anim = 0;
        this.speed = speed;
        this.name = name;
        this.animTime = 0;
        this.touchEnabled = false;
        this.touchChildren = false;

        var resString = Player.RES[index][0];//player_json
        resString = "player_json#" + resString;
        this.spr = new egret.Bitmap(RES.getRes(resString));
        this.addChild(this.spr);

        var blood = new egret.Bitmap(RES.getRes("player_json#blood_1_r_png"));
        blood.x = 20;
        this.addChild(blood);

        var label = new egret.TextField();
        label.textColor = 0xFFFFFF;
        label.text = name;
        label.size = 13;
        label.width = Player.WIDTH;
        label.textAlign = egret.HorizontalAlign.CENTER;
        this.addChild(label);
    }

    public update() {
        //update position
        this.x += this.speed;
        if (this.x >= 1024 + Player.WIDTH) {
            this.x = 1024 - this.x;
        }

        //update anim
        var now = egret.getTimer();
        if (now - this.animTime >= 70) {
            if (++this.anim >= 8) {
                this.anim = 0;
            }

            var resString = Player.RES[this.index][this.anim];//player_json
            resString = "player_json#" + resString;
            this.spr.texture = RES.getRes(resString);
            this.animTime = now;
        }
    }
}


